package com.rop.znyx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rop.znyx.acl.mapper.RoleMapper;
import com.rop.znyx.acl.service.AdminRoleService;
import com.rop.znyx.acl.service.RoleService;
import com.rop.znyx.model.acl.AdminRole;
import com.rop.znyx.model.acl.Role;
import com.rop.znyx.vo.acl.RoleQueryVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/6/13
 * Time: 15:24
 * Description: 角色业务实现层
 */

@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final AdminRoleService adminRoleService;

    /**
     * 获取角色分页列表
     *
     * @param pageParam   分页参数
     * @param roleQueryVo 查询的参数
     * @return 分页查询的结果
     */
    @Override
    public IPage<Role> selectPage(Page<Role> pageParam, RoleQueryVo roleQueryVo) {
        // 查询的角色名称
        String roleName = roleQueryVo.getRoleName();

        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();

        // 判断是否为空
        if (StringUtils.isNotBlank(roleName)) {
            // 添加条件
            wrapper.like(Role::getRoleName, roleName);
        }

        // 返回查询结果
        return baseMapper.selectPage(pageParam, wrapper);
    }

    /**
     * 获取用户所有角色
     *
     * @param id 用户id
     * @return 用户所有角色
     */
    @Override
    @Transactional
    public Map<String, Object> findRoleByUserId(Long id) {

        //查询所有的角色
        List<Role> allRolesList = baseMapper.selectList(null);

        //拥有的角色id
        List<AdminRole> existUserRoleList = adminRoleService.list(new QueryWrapper<AdminRole>().eq("admin_id", id).select("role_id"));
        List<Long> existRoleList = existUserRoleList.stream().map(AdminRole::getRoleId).collect(Collectors.toList());

        //对角色进行分类
        List<Role> assignRoles = new ArrayList<>();
        for (Role role : allRolesList) {
            //已分配
            if (existRoleList.contains(role.getId())) {
                assignRoles.add(role);
            }
        }

        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assignRoles", assignRoles);
        roleMap.put("allRolesList", allRolesList);
        return roleMap;
    }
}
